<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>数据挖掘 | Data Mining Course</title>
    <link rel="stylesheet" href="../../css/main.css" />
    <link rel="stylesheet" href="../../css/tabs.css" />
    <script src="../../js/uikit.js"></script>
    <link href="../../css/prism.css" rel="stylesheet" />
    <script src="../../js/prism.js"></script>
  </head>

  <body>
    <div
      data-uk-sticky="animation: uk-animation-slide-top; sel-target: .uk-navbar-container; cls-active: uk-navbar-sticky; cls-inactive: uk-navbar-transparent; top: 300"
    >
      <nav class="uk-navbar-container pt-2 pb-2">
        <div class="uk-container">
          <div data-uk-navbar>
            <div class="uk-navbar-left">
              <a
                class="uk-navbar-item uk-logo uk-visible@m"
                href="../../index.html"
                >数据挖掘课程</a
              >
              <a
                class="uk-navbar-tuk-containeroggle uk-hidden@m"
                href="#offcanvas-docs"
                data-uk-toggle
                ><span data-uk-navbar-toggle-icon></span>
                <span class="uk-margin-small-left">目录</span></a
              >
              <ul class="uk-navbar-nav uk-visible@m">
                <li><a href="../index.html">文档</a></li>
              </ul>
            </div>
            <div class="uk-navbar-center uk-hidden@m">
              <a class="uk-navbar-item uk-logo" href="../../index.html"
                >数据挖掘课程</a
              >
            </div>
          </div>
        </div>
      </nav>
    </div>

    <div class="uk-section">
      <div class="uk-container">
        <div class="uk-grid-large" data-uk-grid>
          <div class="sidebar-fixed-width uk-visible@m">
            <div class="sidebar-docs uk-position-fixed uk-margin-top">
              <h5>关于这门课</h5>
              <ul class="uk-nav uk-nav-default doc-nav">
                <li><a href="../../index.html">大纲</a></li>
              </ul>
              <h5>章节</h5>
              <ul class="uk-nav uk-nav-default doc-nav">
                <li><a href="../01.html">第1章 - 数据挖掘概念</a></li>
                <li><a href="../02.html">第2章 - 分类</a></li>
                <li><a href="../03.html">第3章 - 聚类</a></li>
                <li><a href="../04.html">第4章 - 关联规则</a></li>
                <li><a href="../05.html">第5章 - 日志的挖掘与应用</a></li>
                <li><a href="../06.html">第6章 - 数据挖掘应用案例</a></li>
              </ul>
              <h5>实验课</h5>
              <ul class="uk-nav uk-nav-default doc-nav">
                <li><a href="./code-01.html">01</a></li>
                <li><a href="./code-02.html">02</a></li>
                <li class="uk-active"><a href="./code-03.html">03</a></li>
                <li><a href="./code-04.html">04</a></li>
                <li><a href="./code-05.html">05</a></li>
                <li><a href="./code-06.html">06</a></li>
                <li><a href="./code-07.html">07</a></li>
                <li><a href="./code-08.html">08</a></li>
                <li><a href="./code-09.html">09</a></li>
                <li><a href="./code-10.html">10</a></li>
                <li><a href="./code-11.html">11</a></li>
                <li><a href="./code-12.html">12</a></li>
                <li><a href="./code-13.html">13</a></li>
                <li><a href="./code-14.html">14</a></li>
                <li><a href="./code-15.html">15</a></li>
                <li><a href="./code-16.html">16</a></li>
              </ul>
            </div>
          </div>
          <div class="uk-width-1-1 uk-width-expand@m">
            <article class="uk-article">
              <h3>SVM人脸识别</h3>
              <div>
                  <p>第0步：在命令提示符(cmd)里分别输入和运行下面内容，安装sklearn和matplotlib包</p>
                  <pre><code class="language-python">pip install --user sklearn</code></pre> 
                  <pre><code class="language-python">pip install --user matplotlib</code></pre> 
                  <p>如果上面的不好用就把--user去掉再运行↓↓↓</p>
                  <pre><code class="language-python">pip install sklearn</code></pre> 
                  <pre><code class="language-python">pip install matplotlib</code></pre> 
                    <p>
                      把下面的所有代码，复制粘贴并保存在一个python文件中，然后运行它，程序会给咱们输出下面这张图。
                      <img src="../../images/lab03/truth-vs-predicted.JPG" alt="truth-vs-predicted">
                      <br>
                    </p>



                    <p>第1步：导入包</p>
                    <pre><code class="language-python">from time import time
import logging
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVC</code></pre>


                    <p>第2步：输出进度日志</p>
                    <pre><code class="language-python">logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')</code></pre>


                    <p>第3步：下载数据并加载为numpy数组(如果是第一次运行，这一步需要花点儿时间去下载)</p>
                    <pre><code class="language-python">lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)</code></pre>
                  
                    <p>第4步：获得图像数组的形状(用于绘图)</p>
                    <pre><code class="language-python">n_samples, h, w = lfw_people.images.shape
X = lfw_people.data
n_features = X.shape[1]
</code></pre>

                    <pre><code class="language-python">#预测的目标是人的ID
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]

print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)</code></pre> 

<p>第5步：切分训练集和测试集</p>
<pre><code class="language-python">X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
t0 = time()
n_components = 150
pca = PCA(n_components=n_components, svd_solver='randomized',whiten=True).fit(X_train)
# 主成分分析进行降维（暂时不理解也没关系）
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))
</code></pre> 


<p>第6步：训练SVM分类模型</p>
<pre><code class="language-python">print("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
              'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'),
                    param_grid, cv=5, iid=False)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)</code></pre> 

<p>第8步：在测试集上评估模型的量化效果</p>
<pre><code class="language-python">pca = PCA(n_components=n_components, svd_solver='randomized',whiten=True).fit(X_train)
print("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done in %0.3fs" % (time() - t0))

print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))</code></pre> 

<p>第9步：使用 matplotlib 定性分析预测结果</p>
<pre><code class="language-python">def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
    plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i], size=12)
        plt.xticks(())
        plt.yticks(())</code></pre> 

<p>第10步：绘制部分测试集的预测结果</p>
<pre><code class="language-python">def title(y_pred, y_test, target_names, i):
    pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
    true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
    return 'predicted: %s\ntrue: %s' % (pred_name, true_name)

prediction_titles = [title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])]

plot_gallery(X_test, prediction_titles, h, w)</code></pre> 

<p>第11步：几个最重要的特征脸的相册</p>
<pre><code class="language-python">plt.show()</code></pre> 

<p>第12步：盘它
  <br>
  如果你给这个文件起名叫svm.py，那么要去运行它，就要在命令行(cmd)里定位到这个文件的位置后，输入下面的内容，然后回车运行。
</p>
<pre><code class="language-python">C:\你的文件夹路径 > python svm.py</code></pre> 
<p>当程序运行到第3步的时候，会下载图片数据，这个过程大约是5到10分钟</p>
<img src="../../images/a-few.JPG" alt="a-few" width="100%">
<p></p>

<p>数据下载好后，程序会继续运行，当运行到第6步代码的时候，程序会告诉咱们能得到最好结果的参数组合</p>
<img src="../../images/lab03/3-step-1.JPG" alt="3-step-1">
<p>最后会弹出人脸识别的结果图。</p>


              </div>
            </article>
          </div>
        </div>
      </div>
    </div>

    <div id="offcanvas-docs" data-uk-offcanvas="overlay: true">
      <div class="uk-offcanvas-bar">
        <button class="uk-offcanvas-close" type="button" data-uk-close></button>
        <h5 class="uk-margin-top">关于这门课</h5>
        <ul class="uk-nav uk-nav-default doc-nav">
          <li><a href="../indext.html">大纲</a></li>
        </ul>
        <h5 class="uk-margin-top">章节</h5>
        <ul class="uk-nav uk-nav-default doc-nav">
          <li><a href="../01.html">第1章 - 数据挖掘概念</a></li>
          <li><a href="../02.html">第2章 - 分类</a></li>
          <li><a href="../03.html">第3章 - 聚类</a></li>
          <li><a href="../04.html">第4章 - 关联规则</a></li>
          <li><a href="../05.html">第5章 - 日志的挖掘与应用</a></li>
          <li><a href="../06.html">第6章 - 数据挖掘应用案例</a></li>
        </ul>
        <h5>实验课</h5>
        <ul class="uk-nav uk-nav-default doc-nav">
          <li><a href="./code-01.html">01</a></li>
          <li><a href="./code-02.html">02</a></li>
          <li class="uk-active"><a href="./code-03.html">03</a></li>
          <li><a href="./code-04.html">04</a></li>
          <li><a href="./code-05.html">05</a></li>
          <li><a href="./code-06.html">06</a></li>
          <li><a href="./code-07.html">07</a></li>
          <li><a href="./code-08.html">08</a></li>
          <li><a href="./code-09.html">09</a></li>
          <li><a href="./code-10.html">10</a></li>
          <li><a href="./code-11.html">11</a></li>
          <li><a href="./code-12.html">12</a></li>
          <li><a href="./code-13.html">13</a></li>
          <li><a href="./code-14.html">14</a></li>
          <li><a href="./code-15.html">15</a></li>
          <li><a href="./code-16.html">16</a></li>
        </ul>
      </div>
    </div>

    <footer class="uk-section uk-text-center uk-text-muted">
      <div class="uk-container uk-container-small">
        <div class="uk-margin-medium"></div>
      </div>
    </footer>

    <script src="../js/awesomplete.js"></script>
    <script src="../js/custom.js"></script>
  </body>
</html>
